<?php

namespace app\model;

use think\Model;
use think\Db;
use app\model\Admin;

class Mch extends Model{
    
    protected $table = 'mm_mch';
    /**
     * Undocumented 创建商户
     *
     * @param [type] $data
     * @return void
     */
    public static function mch_creat($data,$admin_id,$type){
        $Aes = new \Aes();
        $password = $Aes->encrypt(trim($data['pwd']));//加密
        $mch = Mch::create([
            "mch"          => '1000'.mt_rand(1000,9999).'00',//商户号
            "mch_name"     => trim($data['name']),//商户名称
            "password"     => $password,
            "is_agent"     => $data['is_agent'],
            "agent_rate"     => isset($data['agent_rate'])?$data['agent_rate']:0,
            "md5key"       => md5(md5key()),//秘钥
            "agent"        => isset($data['agent'])?$data['agent']:0,//代理商id
            "create_time"  => date("Y-m-d H:i:s",time())
        ]);
       //插入redis
       $list = Mch::select();
       get_list_insert('mch',$list,'mch');
       getLog($admin_id,$type,'创建商户['.$mch->mch.']成功');
        return $mch->id;
    }
    /**
     * Undocumented 更新商户
     *
     * @param [type] $data
     * @return void
     */
    public static function updateMch($data,$admin_id,$role){
        $info = Mch::where("id",$data['mid'])->find();
        if(!$info){
            return '数据不存在';
        }
        Db::startTrans();
        try {
            Mch::where("id",$data['mid'])->update(array(
                "mch_name" => $data['mch_name'],
                "mobile" =>$data['mobile'],
                "email" =>$data['email'],
                "agent_rate" =>!empty($data['agent_rate'])?$data['agent_rate']:0,
                "agent_id" =>!empty($data['agent_id'])?$data['agent_id']:0,
                "status" =>$data['status'],
                "rukuan" =>$data['rukuan'],
                "chukuan" =>$data['chukuan'],
            ));
            getLog($admin_id,$role,'修改商户['.$info->mch.']信息');
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
        get_one_del('mch',$info->mch);
        get_one_insert('mch',$info->mch,['mch'=>$info->mch,'agent_id'=>isset($data['agent_id'])?$data['agent_id']:0,'mch_name'=>$data['mch_name'],'md5key'=>$info->md5key,'chukuan'=>$data['chukuan'],'rukuan'=>$data['rukuan'],'status'=>$data['status']]);
        return true;
    }
    /**
     * Undocumented 添加/修改配置
     *
     * @param [type] $mch
     * @param [type] $data
     * @return void
     */
    public static function mch_config($data){
        
        $arr = $data['act'];
        $result = array();
        $t = [];
        if(is_array($arr)){
            $concurrent = 0;
            foreach ($arr as $k => $v) {
                
                $concurrent = !empty($v['concurrent']) ? $v['concurrent'] : 0;
                if(!empty($v['pid'])){
                    if(empty($v['run_rate'])){
                        return '运营费率不能为空';
                    }
                    //把code一样的数据组成新的数组 支付类型id+运营费率+权重
                    $result[$v['code']][] = $v['pid'].':'.$v['run_rate'].':'.$v['quan'].':'.$concurrent;
                }
            }
        }else{
            return "数据错误";
        }
        if($result){
            foreach ($result as $k => $v) {
                $t[] = $k;
                if(Db::name("mch_channel")->where("mch_id",$data['mch'])->where("code",$k)->find()){
                    //更新
                    Db::name("mch_channel")->where("code",$k)->update(
                        [
                            "payment" =>implode("|",$v) 
                        ]
                    );
                }else{//插入数据
                    Db::name("mch_channel")->where("mch_id",$data['mch'])->insertGetId(
                        [
                            "mch_id" => $data['mch'],
                            "payment" =>implode("|",$v),
                            "code" =>$k
                        ]
                    );
                }
            }
            if($id = Db::name("mch_channel")->where("mch_id",$data['mch'])->where("code",'not in',$t)->column("id")){
               //删除未选中的配置
                Db::name("mch_channel")->where("id",'in',$id)->delete();
            }
        }else{//没有数据，清空商户配置
            Db::name("mch_channel")->where("mch_id",$data['mch'])->delete();
        }
        $list = Db::name("mch_channel")->select();
        //重新导入redis
        get_list_insert("mch_channel",$list,'mch_id');
        return true;
    }
    /**
     * Undocumented 获取代理商名称
     *
     * @param [type] $id
     * @return void
     */
    public static function getAgent($agent_id){
       
        return Mch::where("id",$agent_id)->value("mch_name");
       
    }
      /**
     * Undocumented 根据id获取商户号
     *
     * @param [type] $id
     * @return void
     */
    public static function get_mch_m($agent_id){
       
        return Mch::where("id",$agent_id)->value("mch");
       
    }
     /**
     * Undocumented 获取代理商费率
     *
     * @param [type] $id
     * @return void
     */
    public static function getAgentRate($mch){
        $agent_id = Mch::where("mch",$mch)->value("agent_id");
        if(!empty($agent_id)){//存在代理
            return Mch::where("id",$agent_id)->value("agent_rate");
        }
        return '0';
       
    }
    /**
     * Undocumented 获取商户谷歌秘钥
     *
     * @param [type] $id
     * @return void
     */
    public static function get_mch_google($mch){
       
        return Mch::where("mch",$mch)->value("googl_secret");
       
    }
    /**
     * Undocumented 获取代理商费率
     *
     * @param [type] $id
     * @return void
     */
    public static function get_agent_rate($agent_id){
       
        return abs(Mch::where("id",$agent_id)->value("agent_rate"));
       
    }
    /**
     * Undocumented 获取商户名称
     *
     * @param [type] $id
     * @return void
     */
    public static function getMch($mch){
        
        return Mch::where("mch",$mch)->value("mch_name");
    }
    /**
     * Undocumented 更新商户状态、入金、出款
     *
     * @param [type] $type
     * @param [type] $id
     * @return void
     */
    public static function save_mch($type,$mch){
        switch($type){
            case 'rj'://入金
                $data =  ['rukuan'=>$mch->rukuan == 1 ? 2 : 1];
                break;
            case 'ck'://出款
                $data =  ['chukuan'=>$mch->chukuan == 1 ? 2 : 1];
                break;
            default:  //商户状态
                $data =  ['status'=>$mch->status == 1 ? 2 : 1];
        }
        Db::startTrans();
        try {
            Mch::where("id",$mch->id)->update($data);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
        //重新导入redis
        get_one_del('mch',$mch->mch);
        $info = Mch::where("mch",$mch->mch)->find();
        get_one_insert('mch',$info->mch,$info);
        
        return true;
    }
    /**
     * Undocumented 变更余额
     *
     * @param [type] $data
     * @return void
     */
    public static function editBalance($data,$mch,$mchBalance,$freeze,$is_agent){
        $balance = trim($data['balance']);
        if(empty($balance)){
            return '变更金额要大于0';
        }
        if($data['type'] == 1){//加/减余额
            if($data['status'] == 1){//加余额
                Db::startTrans();
                try {
                    Mch::where("mch",$mch)->setInc("balance",$balance);
                    $remark = trim($data['remark'])?trim($data['remark']) : "手动增加商户:".$balance."元";
                    //商户资金变动记录
                    if($is_agent == 1){
                        mchRecord($mch,$remark,$balance,1);
                    }else{//代理
                        mchAgentRecord($mch,$remark,$balance,1);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }else{//减余额
                if($balance > $mchBalance){//减掉金额不能大于商户余额
                    return '减掉金额不能大于商户余额';
                }
                Db::startTrans();
                try {
                    Mch::where("mch",$mch)->setDec("balance",$balance);
                    $remark = $data['remark']?$data['remark'] : "手动减少商户:".$balance."元";
                    //商户资金变动记录
                    if($is_agent == 1){
                        mchRecord($mch,$remark,$balance,2);
                    }else{//代理
                        mchAgentRecord($mch,$remark,$balance,2);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }
        }else{//冻结/解冻金额
            
            if($data['status'] == 1){//冻结
                if($balance > $mchBalance){//减掉金额不能大于商户余额
                    return '冻结金额不能大于商户余额';
                }
                Db::startTrans();
                try {
                    Mch::where("mch",$mch)->setInc("freeze",$balance);
                    Mch::where("mch",$mch)->setDec("balance",$balance);//冻结金额的同时，减掉余额里面的钱
                    $remark = $data['remark']?$data['remark'] : "手动冻结商户:".$balance."元";
                    if($is_agent == 1){
                        mchRecord($mch,$remark,$balance,3);
                    }else{//代理
                        mchAgentRecord($mch,$remark,$balance,3);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }else{//解冻
                //解冻金额不能大于冻结金额
                if($balance > $freeze){
                    return '解冻金额不能大于冻结金额';
                }
                Db::startTrans();
                try {
                    Mch::where("mch",$mch)->setDec("freeze",$balance);
                    Mch::where("mch",$mch)->setInc("balance",$balance);//解冻同时，余额加钱
                    $remark = $data['remark']?$data['remark'] : "手动解冻商户:".$balance."元";
                    if($is_agent == 1){
                        mchRecord($mch,$remark,$balance,4);
                    }else{//代理
                        mchAgentRecord($mch,$remark,$balance,4);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }
        }
    }
     /**
     * Undocumented 代理商变更余额
     *
     * @param [type] $data
     * @return void
     */
    public static function editAgentBalance($data,$agent,$mchBalance,$freeze){
        $balance = trim($data['balance']);
        if(empty($balance)){
            return '变更金额要大于0';
        }
        if($data['type'] == 1){//加/减余额
            if($data['status'] == 1){//加余额
                Db::startTrans();
                try {
                    Admin::where("id",$agent)->setInc("balance",$balance);
                    $remark = trim($data['remark'])?trim($data['remark']) : "手动增加商户:".$balance."元";
                    //商户资金变动记录
                    mchAgentRecord($agent,$remark,$balance,1);
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }else{//减余额
                if($balance > $mchBalance){//减掉金额不能大于商户余额
                    return '减掉金额不能大于商户余额';
                }
                Db::startTrans();
                try {
                    Admin::where("id",$agent)->setDec("balance",$balance);
                    $remark = trim($data['remark'])?trim($data['remark']) : "手动减少代理商:".$balance."元";
                    //商户资金变动记录
                    mchAgentRecord($agent,$remark,$balance,2);
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }
        }else{//冻结/解冻金额
            
            if($data['status'] == 1){//冻结
                if($balance > $mchBalance){//减掉金额不能大于商户余额
                    return '冻结金额不能大于商户余额';
                }
                Db::startTrans();
                try {
                    Admin::where("id",$agent)->setInc("freeze",$balance);
                    Admin::where("id",$agent)->setDec("balance",$balance);//冻结金额的同时，减掉余额里面的钱
                    $remark = trim($data['remark'])?trim($data['remark']) : "手动冻结代理商:".$balance."元";
                    mchAgentRecord($agent,$remark,$balance,3);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }else{//解冻
                //解冻金额不能大于冻结金额
                if($balance > $freeze){
                    return '解冻金额不能大于冻结金额';
                }
                Db::startTrans();
                try {
                    Admin::where("id",$agent)->setDec("freeze",$balance);
                    Admin::where("id",$agent)->setInc("balance",$balance);//解冻同时，余额加钱
                    $remark = trim($data['remark'])?trim($data['remark']) : "手动解冻代理商:".$balance."元";
                    mchAgentRecord($agent,$remark,$balance,4);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $e->getMessage();
                }
                return true;
            }
        }
    }
    /**
     * Undocumented 统计商户
     *
     * @param [type] $data
     * @return void
     */
    public static function statistical(){

        return Mch::where("is_agent",1)->field("count(id) as max_num,sum(balance) as balance,sum(freeze) as freeze")->find();
    }
    public static function listMch($id){
        $list = Mch::where("agent_id",$id)->field("mch,mch_name")->select();
        $html = "<option value=''>请选择商户</option>";
        foreach ($list as $key => $v) {
            $selected = '';
            $html .= '<option '.$selected.' value='.$v['mch'].'>'.$v['mch'].'['.$v['mch_name'].']</option>';
        }
        return $html;
    }
    /**
     * Undocumented 获取商户信息
     *
     * @param [type] $mch
     * @return void
     */
    public static function get_mch($mch){
        $info = get_one('mch',$mch);
        if(!empty($info)){
            return json_decode(json_encode($info));
        }
        $list = Mch::select();
        get_list_insert('mch',$list,'mch');
        return Mch::where("mch",$mch)->find();
    }
    /**
     * Undocumented 获取商户渠道
     *
     * @param [type] $mch
     * @param [type] $code
     * @return void
     */
    public static function mch_channel($mch,$code){
        $info = get_list('mch_channel',$mch);
        if(empty($info)){
            $list = Db::name('mch_channel')->select();
            get_list_insert('mch_channel',$list,'mch_id');
            return $payment = Db::name("mch_channel")->where("mch_id",$mch)->where("code",$code)->find();
        }
        $payment = array();
        foreach ($info as  $value) {
            if($value['code'] == $code){
                $payment[] = $value;
                break;
            }
        }
        return !empty($payment) ? $payment[0] : $payment;
    }
    /**
     * Undocumented 获取商户余额
     *
     * @param [type] $mch
     * @return void
     */
    public static function mch_balance($mch){

        return Mch::where("mch",$mch)->value("balance");
    }

}




    





?>